<?php
/**
 * List of functions
 *
 * @author Anggiajuang Patria <http://anggiaj.web.id/> 
 */

/*********************
 Image creation functions
 *********************/
 
/**
* Create standard mode email image
*
* @param string Username of email address
* @param string Host of email address
* @param string Extension of email address
* @return resource image
*/
function create_standard_email_image($uname, $host, $ext)
{
	global $EMAIL_HOST;
	$logo_filename 	= STANDARD_LOGO_PATH.$host.'.png';
	$font_family 	= FONT_PATH.STANDARD_FONT_FAMILY.'.ttf';
	$background		= $EMAIL_HOST[$host]['background'];
	$color 			= $EMAIL_HOST[$host]['color'];
	$top 			= (STANDARD_FONT_SIZE) + round(STANDARD_FONT_SIZE/3);
	
	$b = hexa2rgb($background);
	$c = hexa2rgb($color);
	
	// create username layer
	$tmp_layer 	= imagecreatetruecolor(1024, STANDARD_IMAGE_HEIGHT);
	$color 		= imagecolorallocate($tmp_layer, $c['r'], $c['g'], $c['b']);
	$background	= imagecolorallocate($tmp_layer, $b['r'], $b['g'], $b['b']);
	imagefilledrectangle($tmp_layer, 0, 0, 1024, 
		STANDARD_IMAGE_HEIGHT, $background);
	$ttf	 	= imagettftext($tmp_layer, STANDARD_FONT_SIZE, 0, 0, $top, $color, 
		$font_family, $uname);

	// create logo layer
	$logo_layer 				= imagecreatefrompng($logo_filename);
	list($l_width, $l_height) 	= getimagesize($logo_filename);

	// computes layer width and add 2 pixels spaces
	$width = $ttf[2] + 2;
	
	// copy logo layer into tmp layer (username layer) and adjusting position
	imagecopymerge($tmp_layer, $logo_layer, $width, 0, 0, 0, $l_width, 
		STANDARD_IMAGE_HEIGHT, 100);
	imagedestroy($logo_layer);
	
	// create extension layer
	$ext_layer 	= imagecreatetruecolor(1024, STANDARD_IMAGE_HEIGHT);
	$color 		= imagecolorallocate($ext_layer, $c['r'], $c['g'], $c['b']);
	$background	= imagecolorallocate($ext_layer, $b['r'], $b['g'], $b['b']);
	imagefilledrectangle($ext_layer, 0, 0, 1024, STANDARD_IMAGE_HEIGHT, 
		$background);
	$ttf	 	= imagettftext($ext_layer, STANDARD_FONT_SIZE, 0, 0, $top, 
		$color, $font_family, $ext);
	
	// Setting image new width
	$width += $l_width + 2 ;
	// copy extension layer into tmp layer (username layer) and adjusting position
	imagecopymerge($tmp_layer, $ext_layer, $width, 0, 0, 0, 1024, 
		STANDARD_IMAGE_HEIGHT, 100);
	imagedestroy($ext_layer);
	
	// Setting image new width
	$width += $ttf[2];
	
	// create new image layer with the correct width
	$result_image = imagecreate($width, STANDARD_IMAGE_HEIGHT);
	imagecopyresized($result_image, $tmp_layer, 0, 0, 0, 0, $width, 
		STANDARD_IMAGE_HEIGHT, $width, STANDARD_IMAGE_HEIGHT);
	imagedestroy($tmp_layer);
	return $result_image;
}

/**
* Create custom mode email image
*
* @param string Email address
* @param string Font family
* @param int Font size
* @param string Hexa value of font color
* @param string Hexa value of background color
* @return resource image
*/
function create_custom_email_image($email, $font_family, $font_size, $color, 
	$background)
{
	$b = hexa2rgb($background);
	$c = hexa2rgb($color);

	$layer1 = imagecreate(1024,768);

	$background	= imagecolorallocate($layer1, $b['r'], $b['g'], $b['b']);
	$color 		= imagecolorallocate($layer1, $c['r'], $c['g'], $c['b']);

	$ttf = imagettftext($layer1, $font_size, 0, 0, $font_size, $color, 
				$font_family, $email);

	$result_img = imagecreatetruecolor($ttf[2], $ttf[1]);
	imagefilledrectangle($result_img, 0, 0, $ttf[2], $ttf[1], $background);

	imagecopyresized($result_img, $layer1, 0, 0, 0, 0, $ttf[2], $ttf[1], 
		$ttf[2], $ttf[1]);

	imagedestroy($layer1);
	return $result_img;
}

/*********************
 Helper functions
 *********************/
 
/**
* Converting hexa value to RGB array
*
* @param string Hexa value to convert, with '#' prefix. 
* @return RGB array
*/
function hexa2rgb($hexa) 
{
	$rgb = array('r' => 0, 'g' => 0, 'b' => 0);
	$hexa = str_replace('#', '', $hexa);
	$hexa_len = strlen($hexa);
	if ($hexa_len == 6) {
		$hexa = str_split($hexa, 2);
		$rgb['r'] = hexdec($hexa[0]);
		$rgb['g'] = hexdec($hexa[1]);
		$rgb['b'] = hexdec($hexa[2]);
	} else if ($hexa_len == 3) {
		$hexa = str_split($hexa);
		$rgb['r'] = hexdec(str_repeat($hexa[0],2));
		$rgb['g'] = hexdec(str_repeat($hexa[1],2));
		$rgb['b'] = hexdec(str_repeat($hexa[2],2));	
	}
	return $rgb;
}

/**
* Give needed header and display image
*
* @param resource Email image to display
* @return void
*/
function display_email_image($image)
{
	set_expires();		
	header('Content-type: image/png');
	imagepng($image);
	imagedestroy($image);
}

/**
* Give needed header and outputting json
*
* @param string CSS class
* @param string Text to output
* @return void
*/
function json_out($class, $text)
{
	set_expires();
	header('Content-type: text/x-json');
	echo json_encode(array(	
				'class' => $class, 
				'text' => $text, 
				'hits' => display_hits()
	));
}

/**
* Set expires to content
*
* @return void
*/
function set_expires()
{
	header('Cache-Control: no-cache, must-revalidate'); // HTTP/1.1
	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
}

/*********************
 Counter functions
 *********************/

/**
* Increasing hits
*
* @return void
*/ 
function increase_hits()
{
	$counter = (int)file_get_contents(COUNTER_FILENAME);
	$counter++;
	file_put_contents(COUNTER_FILENAME, $counter); 
}

/**
* Displaying hits
*
* @return string
*/
function display_hits()
{
	$counter = (int)file_get_contents(COUNTER_FILENAME);
	return 'Total ' . $counter . ' generate image, since ' . START_DATE;
}

/*********************
 Data validation functions
 *********************/
 
/**
* Validate a email
*
* Original from PEAR::QuickForm::Rule v 1.4  by: Bertrand Mansion <bmansion@mamasam.com> 
* 
* @param string    $email          URL to validate
* @param boolean   $domain_check   Check or not if the domain exists
*/
function validate_email($email, $check_domain = false)
{
	$regex = '/^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/';
	
	if (preg_match($regex, $email)) {
        if ($check_domain and function_exists('checkdnsrr')) {
            $tokens = explode('@', $email);
            if (checkdnsrr($tokens[1], 'MX') || checkdnsrr($tokens[1], 'A')) {
                return true;
            }
            return false;
        }
        return true;
    }
    return false;
}
?>